#include <SDL.h>
#include "controller.h"

Controller::~Controller() {
  atexit(SDL_Quit);
}

void Controller::play() {
  SDL_Event event;
  bool keyCatch = true;
  bool done = false;
  while ( ! done ) {
	model.draw();
	model.update();
    SDL_PollEvent(&event);
    Uint8 *keystate = SDL_GetKeyState(NULL);

    switch (event.type) {
      case SDL_QUIT: {
        done = true;
        break;
      }
      case SDL_KEYUP: {
		//if((keystate[SDLK_UP] )||(keystate[SDLK_DOWN] )||(keystate[SDLK_LEFT] )||(keystate[SDLK_RIGHT] )){
			keyCatch = true;
			model.stop();

		//}
      }
      case SDL_KEYDOWN: {
        if (keystate[SDLK_q] || keystate[SDLK_ESCAPE]) {
          done = true;
        }
        if ( (keystate[SDLK_F1] || keystate[SDLK_p] )&& keyCatch) {
		  model.toggleHelp();
		  keyCatch = false;
        }
        if(!model.isPaused())
        {
			if ((keystate[SDLK_m]) && keyCatch) {
			  model.toggleBgm();
			  keyCatch = false;
			}

			//if ( keystate[SDLK_UP] ) {
			  //model.move(1);
			//}
			//if ( keystate[SDLK_DOWN] ) {
			  //model.move(2);
			//}
			if ( keystate[SDLK_LEFT] ) {
			  model.move(3);
			}
			if ( keystate[SDLK_RIGHT] ) {
			  model.move(4);
			}
			if ( keystate[SDLK_e] && keyCatch ) {
			  model.explode();
			  keyCatch = false;
			}
			
			if ( keystate[SDLK_r] && keyCatch ) {
			  model.resetBricks();
			  keyCatch = false;
			}
			
			if((keystate[SDLK_1] || keystate[SDLK_2])
				&& keyCatch)
			{
				int sound = event.key.keysym.sym - SDLK_0;
				model.playSound(sound);
				keyCatch = false;
			}
		}
        
        break;
      }
    }
  }
}
